﻿<!--采购供应商-->
<template>
  <div class="supplier-management-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
      <button class="btn-new" @click="handleAdd">新建</button>
        <div class="filter-item">
          <label>关键词</label>
          <input type="text" placeholder="请输入供应商编号/供应商名称" v-model="queryParams.keyword">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="queryParams.status">
            <option value="">全部</option>
            <option value="0">启用</option>
            <option value="1">停用</option>
          </select>
        </div>
        <div class="actions">
          <button class="btn-primary" @click="handleSearch">搜索</button>
          <button class="btn-secondary" @click="resetQuery">重置</button>
        </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected" @change="handleSelectionChange"></th>
            <th>供应商名称</th>
            <th>供应商编号</th>
            <th>联系人</th>
            <th>联系人职位</th>
            <th>联系电话</th>
            <th>微信</th>
            <th>邮箱</th>
            <th>详细地址</th>
            <th>备注</th>
            <th>状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="11" style="text-align: center; padding: 20px;">加载中...</td>
          </tr>
          <tr v-else-if="suppliers.length === 0">
            <td colspan="11" style="text-align: center; padding: 20px;">暂无数据</td>
          </tr>
          <tr v-else v-for="(item, index) in suppliers" :key="index">
            <td><input type="checkbox" v-model="item.selected" @change="handleSelectionChange"></td>
            <td class="link-style">{{ item.supplierName }}</td>
            <td>{{ item.supplierCode }}</td>
            <td>{{ item.contactName || "-" }}</td>
            <td>{{ item.contactPosition || "-" }}</td>
            <td>{{ item.contactPhone || "-" }}</td>
            <td>{{ item.wechat || "-" }}</td>
            <td>{{ item.email || "-" }}</td>
            <td>{{ item.address || "-" }}</td>
            <td>{{ item.remark || "-" }}</td>
            <td>
              <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected" @change="handleSelectionChange">
        <label>全选</label>
        <button class="btn-secondary" @click="handleExport">导出</button>
      </div>
      <div class="pagination">
        <el-pagination
          background
          layout="sizes, prev, pager, next"
          :page-sizes="[5,10,20,50]"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="uId">
          <el-select v-model="form.uId" placeholder="请选择联系人">
            <el-option v-for="user in users" :key="user.userId" :label="user.username" :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人职位" prop="contactPosition">
          <el-input v-model="form.contactPosition" placeholder="请输入联系人职位"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="form.wechat" placeholder="请输入微信"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { pagePurchaseSuppliers, addPurchaseSupplier, listSupplierUsers } from "@/api/purchase/PurchaseSupplier";
import { ElMessage } from "element-plus";

export default {
  name: "SupplierManagement",
  data() {
    return {
      loading: false,
      suppliers: [],
      allSuppliers: [],
      total: 0,
      currentPage: 1,
      clientPaging: false,
      debugInfo: "页面已加载",
      queryParams: {
        keyword: "",
        status: "",
        pageNum: 1,
        pageSize: 10,
      },
      dialogVisible: false,
      dialogTitle: "新增供应商",
      form: {
        supplierName: "",
        uId: null,
        contactPosition: "",
        contactPhone: "",
        wechat: "",
        email: "",
        address: "",
        status: 0,
        remark: "",
      },
      rules: {
        supplierName: [
          { required: true, message: "请输入供应商名称", trigger: "blur" }
        ],
      },
      users: [],
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.suppliers.length > 0 && this.suppliers.every(item => item.selected);
      },
      set(value) {
        this.suppliers.forEach(item => {
          item.selected = value;
        });
      }
    },
    totalPages() {
      return Math.ceil(this.total / this.queryParams.pageSize);
    }
  },
  created() {
    this.debugInfo = "组件已创建，准备获取数据";
    this.loadUsers();
    this.getList();
  },
  methods: {
    async getList() {
      this.loading = true;
      this.debugInfo = "正在获取数据...";
      try {
        console.log("发送请求参数:", this.queryParams);
        const res = await pagePurchaseSuppliers(this.queryParams);
        console.log("API响应:", res);
        // 兼容两种返回：axios 原始响应(res) 或 直接返回数据(res.data)
        const payload = res && res.data ? res.data : res;
        this.debugInfo = "API响应: " + JSON.stringify(payload);

        if (payload && payload.code === 200) {
          const page = payload.data || { records: [], total: 0 };
          const list = (page.records || []).map(item => ({
            ...item,
            selected: false
          }));
          if (this.clientPaging) {
            // 前端本地分页
            this.allSuppliers = list
            this.total = this.allSuppliers.length
            this.sliceClientPage()
          } else {
            this.suppliers = list
            this.total = page.total || list.length || 0
          }
          this.debugInfo = `获取成功`;
        } else {
          const msg = (payload && (payload.msg || payload.message)) || "未知错误";
          this.debugInfo = "获取失败: " + msg;
          ElMessage.error(msg || "获取数据失败");
        }
      } catch (error) {
        console.error("获取供应商列表失败:", error);
        this.debugInfo = "请求异常: " + error.message;
        ElMessage.error("获取供应商列表失败");
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        keyword: "",
        status: "",
        pageNum: 1,
        pageSize: 10,
      };
      this.getList();
    },
    onCurrentChange(page) {
      this.currentPage = page;
      this.queryParams.pageNum = page;
      if (this.clientPaging) {
        this.sliceClientPage()
      } else {
        this.getList()
      }
    },
    onSizeChange(size) {
      this.queryParams.pageSize = size;
      this.currentPage = 1;
      this.queryParams.pageNum = 1;
      if (this.clientPaging) {
        this.sliceClientPage()
      } else {
        this.getList()
      }
    },
    sliceClientPage() {
      const start = (this.currentPage - 1) * this.queryParams.pageSize
      const end = start + Number(this.queryParams.pageSize)
      this.suppliers = this.allSuppliers.slice(start, end)
    },
    handleSelectionChange() {
      // 处理选择变化
    },
    handleAdd() {
      this.dialogTitle = "新增供应商";
      this.form = {
        supplierName: "",
        uId: null,
        contactPosition: "",
        contactPhone: "",
        wechat: "",
        email: "",
        address: "",
        status: 0,
        remark: "",
      };
      this.dialogVisible = true;
    },
    async handleSubmit() {
      try {
        const res = await addPurchaseSupplier(this.form);
        const payload = res && res.data ? res.data : res;
        if (payload && payload.code === 200) {
          ElMessage.success("新增成功");
          this.dialogVisible = false;
          this.getList();
        } else {
          ElMessage.error((payload && (payload.msg || payload.message)) || "新增失败");
        }
      } catch (error) {
        console.error("新增供应商失败:", error);
        ElMessage.error("新增供应商失败");
      }
    },
    async loadUsers() {
      try {
        const res = await listSupplierUsers();
        const payload = res && res.data ? res.data : res;
        if (payload && payload.code === 200) {
          // 兼容字段名
          const list = payload.data || [];
          this.users = list.map(u => ({ userId: u.userId, username: u.username }));
        }
      } catch (e) {
        console.error("加载联系人失败", e);
      }
    },
    handleExport() {
      ElMessage.info("导出功能开发中");
    },
    getStatusText(status) {
      return status === 0 ? "启用" : status === 1 ? "停用" : "未知";
    },
    getStatusClass(status) {
      return status === 0 ? "status-enabled" : status === 1 ? "status-disabled" : "status-unknown";
    }
  }
}
</script>

<style scoped>
.supplier-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.btn-new {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    margin-left: 10px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.filter-item input {
    width: 200px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.status-enabled {
  color: #67c23a;
  font-weight: 500;
}

.status-disabled {
  color: #f56c6c;
  font-weight: 500;
}

.status-unknown {
  color: #909399;
  font-weight: 500;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
